package com.newcapec.repair.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.newcapec.repair.R;
import com.newcapec.repair.config.APPConfig;
import com.newcapec.repair.entity.Result;
import com.newcapec.repair.utils.HttpUtils;


import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private ImageView verifyImg;
    private TextView changeText;
    private EditText userNameEdit,userPwdEdit,verifyCodeEdit;

    private Button logBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();

        loadImg();
    }

    private void initView(){
        verifyImg = findViewById(R.id.verifyImg);
        changeText = findViewById(R.id.changeText);
        userNameEdit = findViewById(R.id.userName);
        userPwdEdit = findViewById(R.id.userPwd);
        verifyCodeEdit = findViewById(R.id.verifyCode);

        logBtn = findViewById(R.id.logBtn);
        changeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadImg();
            }
        });

        logBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login(){
        OkHttpClient client = HttpUtils.getClient();
        String userName = userNameEdit.getText().toString();
        String userPwd = userPwdEdit.getText().toString();
        String verifyCode = verifyCodeEdit.getText().toString();
        if (userName.equals("")) {
            showMsg("用户名不能为空");
            return;
        }

        if (userPwd.equals("")) {
            showMsg("密码不能为空");
            return;
        }

        if (verifyCode.equals("")) {
            showMsg("验证码不能为空");
            return;
        }

        RequestBody formBody = new FormBody.Builder()
                .add("userName", userName)
                .add("userPwd", userPwd)
                .add("verifyCode", verifyCode)
                .build();
        final Request request = new Request.Builder()
                .url(APPConfig.LOGIN_URL)
                .post(formBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //此处涉及到ui操作，只能在主线程中操作ui
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showMsg("请求服务器失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Result result = JSON.parseObject(response.body().string(),Result.class);
                            if(result.getCode() == 200){
                                showMsg("登录成功");
                                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                showMsg(result.getMsg());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });


    }

    private void loadImg(){
        //发起http请求,请求到验证码后，加载到图标中
        OkHttpClient client = HttpUtils.getClient();
        final Request request = new Request.Builder()
                .url(APPConfig.VERIFY_CODE_URL)
                .get()
                //.addHeader("mobile", "mobile")
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //此处涉及到ui操作，只能在主线程中操作ui
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showMsg("请求服务器失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[] img = response.body().bytes();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
                        //通过imageview，设置图片
                        verifyImg.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }

    public void showMsg(String msg) {
        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

}